<?php

namespace app\admin\model;

use think\Model;

class Category extends Model
{

    protected $table = 'hyper_categories';

    private static $instance = null;

    public function getAddTimeAttr($time)
    {
        return date('Y-m-d H:i:s', $time);
    }

    public static function getInstance()
    {
        //检测当前类属性$instance是否已经保存了当前类的实例
        if (self::$instance == null) {
            //如果没有,则创建当前类的实例
            self::$instance = new self();
        }
        //如果已经有了当前类实例,就直接返回,不要重复创建类实例
        return self::$instance;
    }

    public function getCategories($num = 15)
    {
        $where = "";
        $param = [];
        $categories = $this->field('*')
            ->where($where)
            ->order('order', 'DESC')
            ->paginate($num, false, ['query' => $param]);

        $page = $categories->render();// 获取分页显示

        if ($categories) {
            return ['code' => 1, 'data' => $categories, 'msg' => '数据查询成功', 'page' => $page];
        } else {
            return ['code' => 2, 'data' => '', 'msg' => '暂无数据', 'page' => ''];
        }
    }

    public function getAll($where = array(), $field = '*')
    {
        $data = $this->field($field)->where($where)->select()->toArray();
        return $data;
    }

    public function getOne($where, $field = '*')
    {
        return $this->field($field)->where($where)->find();
    }

    /**
     * @Title: editCategory
     * @Description: 编辑分类信息
     * @param $param
     * @return mixed
     * @Author: 李军伟
     */
    public function editCategory($param)
    {
        $this->allowField(true)->isUpdate(true)->save($param, ['id' => $param['id']]);

        return $this->id;
    }

    public function delCategory($id)
    {
        return $this->where(array('id' => $id))->delete();
    }

    public function getAllByPage($where, $page, $limit = 15)
    {
        $list = $this->where($where)->limit(($page - 1) * $limit, $limit)->select()->toArray();
        $count = $this->where($where)->count();
        return array(
            'list' => $list,
            'total_page' => ceil($count / 10),
        );
    }
}
